package com.seeyon.apps.kkTimedTaskSharing.manager;


import com.seeyon.apps.kkTimedTaskSharing.utils.SqlUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.event.FormDataAfterSubmitEvent;
import com.seeyon.cap4.form.service.CAP4FormCacheManager;
import com.seeyon.cap4.form.util.Enums;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.quartz.QuartzHolder;
import com.seeyon.ctp.common.quartz.QuartzJob;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.AjaxAccess;
import com.seeyon.ctp.util.annotation.ListenEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 作者
 * @Description: 描述
 * @Date: 创建于11:43 2024-04-02
 **/
@Component("kkTimedTaskSharingManager")
public class KKTimedTaskSharingManagerImpl implements KKTimedTaskSharingManager {

    private static final Log log = LogFactory.getLog(KKTimedTaskSharingManagerImpl.class);

    private CAP4FormCacheManager cap4FormCacheManager;

    private FormApi4Cap4 formApi4Cap4;

    private EnumManager enumManagerNew;

    private OrgManager orgManager;

    // jobName 前缀，以防万一，比如，定时任务表被删除了，定时任务数据被突然清空了，这里需要对任务加个前缀
    private String prefix = "scheduledtasks-";

    private final static String TEMPLETECODE = AppContext.getSystemProperty("kkTimedTaskSharing.taskTemplateCode");

    @Override
    public void init() {
        try {
            //获取 定时任务底表的数据信息
            FormBean formBean = null;
            log.info("=================开始初始化信息定时任务");
            log.info("TEMPLETECODE:" + TEMPLETECODE);
            formBean = formApi4Cap4.getFormByFormCode(TEMPLETECODE);
            StringBuilder sql = new StringBuilder("select id from " + formBean.getMasterTableBean().getTableName());
            List<Map<String, Object>> list = SqlUtil.doQuery(sql.toString(), null);
            if (Strings.isNotEmpty(list)) {
                for (Map<String, Object> map : list) {
                    // 捕获异常，不让个别任务异常而导致其他任务启动失败
                    try{
                        Long id = ParamUtil.getLong(map, "id");
                        FormDataMasterBean formData = formApi4Cap4.findDataById(id, formBean, null);
                        Map<String, String> fieldDisplayMap = formBean.getAllFieldDisplayMap();
                        if (formData != null) {
                            // 将定时任务bean名称
                            Object jobName = formData.getFieldValue(fieldDisplayMap.get("定时任务ID"));
                            Object beanName = formData.getFieldValue(fieldDisplayMap.get("定时任务bean名称"));
                            Object beanExecutionTime = formData.getFieldValue(fieldDisplayMap.get("设置定时任务执行时间"));
                            Object enabled = formData.getFieldValue(fieldDisplayMap.get("是否启用"));
                            if (jobName != null && beanName != null && beanExecutionTime != null && enabled != null) {
                                //删除已有任务
                                String jobNameStr = prefix+String.valueOf(jobName);
                                String beanNameStr = String.valueOf(beanName);
                                String beanExecutionTimeStr = String.valueOf(beanExecutionTime);
                                if (QuartzHolder.hasQuartzJob(jobNameStr)) {
                                    QuartzHolder.deleteQuartzJob(jobNameStr);
                                    log.info("delete,jobName:"+jobNameStr+",beanName:" + beanNameStr + ",beanExecutionTimeStr=" + beanExecutionTimeStr);
                                }
                                FormFieldBean enabledField = formBean.getFieldBeanByDisplay("是否启用");
                                CtpEnumItem cacheEnumItem = enumManagerNew.getCacheEnumItem(Long.valueOf(String.valueOf(enabled)));
                                if (cacheEnumItem!=null && cacheEnumItem.getShowvalue().equals("启用")) {
                                    // 如果是停用 不进行创建，仅删除
                                    // 新建任务
                                    QuartzHolder.newCronQuartzJob(null, jobNameStr, beanExecutionTimeStr, null, null, beanNameStr, null);
                                    log.info("create,jobName:"+jobNameStr+",beanName:" + beanNameStr + ",beanExecutionTimeStr=" + beanExecutionTimeStr);
                                }
                            }
                        }
                    }catch (Exception e){
                        log.error("#任务配置读取失败#" + e.getMessage(), e);
                    }
                }
            }
            log.info("定时任务初始化结束");
        } catch (Exception e) {
            log.error("#定时配置读取#" + e.getMessage(), e);
        }
    }


    /**
     * @Description: 底表数据变更事件 保存前事件 FormDataBeforeSubmitEvent
     * 保存后事件是：FormDataAfterSubmitEvent
     * @param event
     * @Author: user
     * @Date: 2023/4/13 10:01
     */
    @ListenEvent(event = FormDataAfterSubmitEvent.class, async = true)
    public void getFormDataAfterSubmitEvent(FormDataAfterSubmitEvent event) throws BusinessException {
        log.info("method:getFormDataAfterSubmitEvent start");
        FormDataMasterBean formData = (FormDataMasterBean)event.getSource();
        try {

            FormTableBean tableBean = formData.getFormTable();
            log.info("---------------tabbleBean"+tableBean);
            FormBean formBean = cap4FormCacheManager.getForm(tableBean.getFormId());

            if (formBean!= null && Enums.FormType.unFlowForm.getKey() == formBean.getFormType()) {
                // 如果操作的是定时任务底表
                if (formBean.getBind()!=null && formBean.getBind().getFormCode().equals(TEMPLETECODE)){
                    Map<String, String> fieldDisplayMap = formBean.getAllFieldDisplayMap();
                    // 将定时任务bean名称
                    Object jobName = formData.getFieldValue(fieldDisplayMap.get("定时任务ID"));
                    Object beanName = formData.getFieldValue(fieldDisplayMap.get("定时任务bean名称"));
                    Object beanExecutionTime = formData.getFieldValue(fieldDisplayMap.get("设置定时任务执行时间"));
                    Object enabled = formData.getFieldValue(fieldDisplayMap.get("是否启用"));
                    log.info("定时任务配置信息：jobName="+jobName+",beanName="+beanName+",beanExecutionTime="+beanExecutionTime+",enabled="+enabled);
                    if (jobName != null && beanName != null && beanExecutionTime != null && enabled != null) {
                        //删除已有任务
                        String jobNameStr = prefix+String.valueOf(jobName);
                        String beanNameStr = String.valueOf(beanName);
                        String beanExecutionTimeStr = String.valueOf(beanExecutionTime);
                        if (QuartzHolder.hasQuartzJob(jobNameStr)) {
                            QuartzHolder.deleteQuartzJob(jobNameStr);
                            log.info("delete,jobName:"+jobNameStr+",beanName:" + beanNameStr + ",beanExecutionTimeStr=" + beanExecutionTimeStr);
                        }
                        FormFieldBean enabledField = formBean.getFieldBeanByDisplay("是否启用");
                        CtpEnumItem cacheEnumItem = enumManagerNew.getCacheEnumItem(Long.valueOf(String.valueOf(enabled)));
                        if (cacheEnumItem!=null && cacheEnumItem.getShowvalue().equals("启用")) {
                            // 如果是停用 不进行创建，仅删除
                            // 新建任务
                            QuartzHolder.newCronQuartzJob(null, jobNameStr, beanExecutionTimeStr, null, null, beanNameStr, null);
                            log.info("create,jobName:"+jobNameStr+",beanName:" + beanNameStr + ",beanExecutionTimeStr=" + beanExecutionTimeStr);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
    }



    @Override
    @AjaxAccess
    public Map<String, Object> taskExecute(Map<String, Object> map) {
        log.info("=================任务执行开始");
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try{
            List rowData = (List) map.get("rowData");
            if (Strings.isNotEmpty(rowData)){
                log.info("rowData:"+rowData.size());
                log.info("TEMPLETECODE:"+TEMPLETECODE);
                FormBean formBean = formApi4Cap4.getFormByFormCode(TEMPLETECODE);
                for (Object row : rowData) {
                    Long dataId = Long.valueOf(row.toString());
                    if (formBean!=null) {
                        FormDataMasterBean formDataMasterBean = null;
                        formDataMasterBean = formApi4Cap4.getSessioMasterDataBean(dataId);  //从缓存中获取主表数据
                        if (formDataMasterBean==null){
                            formDataMasterBean = formApi4Cap4.findDataById(Long.valueOf(dataId), formBean, null);
                        }
                        if (formDataMasterBean!=null){
                            FormFieldBean formFieldBean = formBean.getFieldBeanByDisplay("定时任务bean名称");
                            if (formFieldBean!=null){
                                Object fieldValue = formDataMasterBean.getFieldValue(formFieldBean.getName());
                                if (Strings.isNotEmpty(String.valueOf(fieldValue))){
                                    String beanName = String.valueOf(fieldValue);
                                    QuartzJob bean = (QuartzJob)AppContext.getBean(beanName);
                                    bean.execute(null);
                                }
                            }
                        }else {
                            log.info("formDataMasterBean is null");
                        }
                    }else {
                        log.info("formBean is null");
                    }
                }
            }
            returnMap.put("code",0);
        }catch (Exception e){
            log.error("getLinksAndSerialNumbers:"+e.getMessage(), e);
            returnMap.put("code",-1);
        }
        return returnMap;
    }


    public CAP4FormCacheManager getCap4FormCacheManager() {
        return cap4FormCacheManager;
    }

    public void setCap4FormCacheManager(CAP4FormCacheManager cap4FormCacheManager) {
        this.cap4FormCacheManager = cap4FormCacheManager;
    }

    public OrgManager getOrgManager() {
        return orgManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public EnumManager getEnumManagerNew() {
        return enumManagerNew;
    }

    public void setEnumManagerNew(EnumManager enumManagerNew) {
        this.enumManagerNew = enumManagerNew;
    }

    public FormApi4Cap4 getFormApi4Cap4() {
        return formApi4Cap4;
    }

    public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
        this.formApi4Cap4 = formApi4Cap4;
    }
}

